<template>
  <div>
    <!-- 标题 -->
    <van-nav-bar
      title="更改头像"
      left-arrow
      @click-left="onClickLeft"
    >
    </van-nav-bar>
    <div class="img_box">
      <van-image
        :src="'apis/kuan_api/photo/'+this.$store.state.user.user_img"
        class="img"
      />
    </div>
    <div style="text-align:center">
      <van-uploader :after-read="afterRead">
        <van-button
          type="primary"
          class="btn"
        >选择图片</van-button>
      </van-uploader>
    </div>
  </div>
</template>

<script>
export default {
  name: "changephoto",
  data() {
    return {};
  },
  methods: {
    //   返回上一级
    onClickLeft() {
      window.history.go(-1);
    },
    afterRead(file) {
      let type = file.file.type;
      let filelist = file.file;
      if (type == "image/jpeg" || type == "image/png" || type == "image/jpg") {
        let userid = this.$store.state.user.user_id;
        let param = new FormData();
        let config = { headers: { "Content-Type": "multipart/form-data" } };
        param.append("file", filelist);
        param.append("user_id", userid);
        this.axios
          .post("apis/kuan_api/setPhoto.php", param, config)
          .then((res) => {
            this.$toast.success("修改成功");
            this.getuser();
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        this.$toast.fail("请选择正确的图片格式");
      }
    },

    getuser() {
      this.axios
        .post("apis/kuan_api/searchUser.php", {
          userid: this.$store.state.user.user_id,
        })
        .then((res) => {
          sessionStorage.setItem("user", JSON.stringify(res.data.users[0]));
          this.$store.state.user = res.data.users[0];
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>

<style scoped>
.img_box {
  width: 95%;
  margin: 80px auto;
}
.btn {
  width: 140px;
  height: 35px;
}
.img {
  width: 100%;
}
</style>